import { Component, Input, Output, EventEmitter, OnInit, HostBinding } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Location } from '@angular/common';

import { Hero } from '../shared/hero.model';
import { HeroService } from '../shared/hero.service';

@Component({
    selector: 'hero-detail',
    templateUrl: './hero-detail.component.html',
    styleUrls: ['./hero-detail.component.css'],
    // Alternatively, you can identify members in the inputs and outputs arrays of the directive metadata.
    // BUT NOT RECOMMENDED.
    // inputs: ['hero'],
    // outputs: ['deleteRequest:delete']
})
export class HeroDetailComponent implements OnInit {
    @HostBinding('@routeAnimation') routeAnimation = true;
    @HostBinding('style.display') display = 'block';
    @HostBinding('style.position') position = 'absolute';

    // Parent can bind to the 'hero' property to pass in the Hero data.
    @Input() hero: Hero;

    // Parent can bind to the 'deleteRequest' customized event to register the event handler.
    // You can specify the alias for the property name by passing it into the input/output decorator like this.
    // But should avoid aliasing inputs and outputs.
    @Output() deleteRequest: EventEmitter<Hero> = new EventEmitter<Hero>();

    constructor(
        private heroService: HeroService,
        private route: ActivatedRoute,
        private router: Router,
        private location: Location
    ) { }

    ngOnInit(): void {
        // Two older properties are still available. They are less capable than their replacements, discouraged, 
        // and may be deprecated in a future Angular version.

        // params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

        // queryParams — An Observable that contains the query parameters available to all routes. Use queryParamMap instead.

        // +params['id']
        // (+) before params['id'] turns the string into a number
        // this.route.params
        //     .switchMap((params: Params) => this.heroService.getHero(+params['id']))
        //     .subscribe(hero => this.hero = hero);

        // this.route.paramMap
            // .switchMap((params: ParamMap) => this.heroService.getHero(params.get('id')))
            // .subscribe(hero => this.hero = hero);
    }

    // save(): void {
    //     this.heroService.update(this.hero)
    //         .then(() => this.goBack());
    // }

    delete(): void {
        this.deleteRequest.emit(this.hero);
    }

    goBack(): void {
        // Pass along the hero id if available as optional parameter.
        // so that the HeroList component can select that hero.
        // Include a junk 'foo' property for fun.
        this.router.navigate(['/heroes', {id: this.hero.id, foo: 'foo', hero: JSON.stringify(this.hero)}]);

        // this.location.back();
    }
}